/*
	       File: HTTPPost.cs
	Create Date: 2007-12-1
	    Version:

	Description:


*/
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Net;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;

using GuerillaProgrammer.Components;
using GuerillaProgrammer.Components.Logging;

namespace GuerillaProgrammer.FileProcessor.Activities
{
    public partial class HTTPPost : Activity
    {
        #region Private member fields
        private string _URL;
        private string _UploadSource;
        private string _DownloadPath;
        private bool _IgnoreResponse;
        #endregion

        #region Constructors and cleanup methods
        public HTTPPost()
        {
            InitializeComponent();
        }
        #endregion

        #region Private implementation methods
        #endregion

        #region Class properties
        public static DependencyProperty URLProperty = System.Workflow.ComponentModel.DependencyProperty.Register("URL", typeof(string), typeof(HTTPPost));
        [Description("URL of the file to be downloaded.")]
        [Category("HTTP GET")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string URL
        {
            get { return _URL; }
            set { _URL = value; }
        }
        public static DependencyProperty UploadSourceProperty = System.Workflow.ComponentModel.DependencyProperty.Register("UploadSource", typeof(string), typeof(HTTPPost));
        [Description("Path to the source being posted")]
        [Category("HTTP GET")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string UploadSource
        {
            get { return _UploadSource; }
            set { _UploadSource = value; }
        }
        public static DependencyProperty DownloadPathProperty = System.Workflow.ComponentModel.DependencyProperty.Register("DownloadPath", typeof(string), typeof(HTTPPost));
        [Description("Path to put the downloaded response")]
        [Category("HTTP GET")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string DownloadPath
        {
            get { return _DownloadPath; }
            set { _DownloadPath = value; }
        }
        public static DependencyProperty IgnoreResponseProperty = System.Workflow.ComponentModel.DependencyProperty.Register("IgnoreResponse", typeof(bool), typeof(HTTPPost));
        [Description("Ignore the response, dont write anything.")]
        [Category("HTTP GET")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public bool IgnoreResponse
        {
            get { return _IgnoreResponse; }
            set { _IgnoreResponse = value; }
        }

        #endregion

        #region Events handlers
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                Logger.LogEnter();

                IProcessorDataService dataService = executionContext.GetService(typeof(IProcessorDataService)) as IProcessorDataService;
                if (null == dataService)
                {
                    throw new InvalidOperationException("Can't get the service!");
                }

                WorkItem workItem = dataService.GetWorkItem();
                StringProcessor stringProcessor = new StringProcessor(new FileProcessorSymbolTable(dataService.GetConfiguration(), workItem));
                
                //expand out all the Macros
                string url = stringProcessor.SubstituteStringValues(URL);
                string uploadSource = stringProcessor.SubstituteStringValues(UploadSource);
                string downloadDestination;

                if (false == _IgnoreResponse)
                {
                    downloadDestination = stringProcessor.SubstituteStringValues(DownloadPath);
                }
                else
                {
                    downloadDestination = "";
                }
                Logger.LogInfo("HTTPPost", "Posting to {0}\nSource: {1}", url, uploadSource);
                WebRequest request = WebRequest.Create(url);
                request.Credentials = CredentialCache.DefaultCredentials;
                StreamReader reader = new StreamReader(uploadSource);
                request.Method = "POST";
                StreamWriter requestStream = new StreamWriter(request.GetRequestStream());
                requestStream.Write(reader.ReadToEnd());
                reader.Close();
                requestStream.Flush();
                requestStream.Close();
                Logger.LogInfo("HTTPost", "Post complete");

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (false == IgnoreResponse)
                {
                    //Now get the response
                    StreamReader responseReader = new StreamReader(response.GetResponseStream());
                    StreamWriter responseWriter = new StreamWriter(downloadDestination, false);
                    responseWriter.Write(responseReader.ReadToEnd());
                    responseWriter.Close();
                    responseReader.Close();
                    Logger.LogInfo("HTTPPost", "Download complete");
                }
                else
                {
                    Logger.LogInfo("HTTPPost", "Ignoring server response.");
                }
                response.Close();

                Logger.LogLeave();
                return base.Execute(executionContext);
            }
            catch (Exception exc)
            {
                Logger.LogError("HTTPPost ERROR", "An error occured in HTTPPost!\nError: {0}", exc.Message);
                Logger.LogLeave();

                return ActivityExecutionStatus.Faulting;
            }
        }
        #endregion
	}
}
